//
//  TableViewController.m
//  
//
//  Created by student on 16/3/28.
//
//

#import "TableViewController.h"
#import <UIImageView+WebCache.h>
#import "Video.h"
@interface TableViewController ()
@property (nonatomic,strong)NSMutableArray *list;
@end

@implementation TableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    UIRefreshControl *c = [[UIRefreshControl alloc]init];
    c.attributedTitle = [[NSAttributedString alloc] initWithString:@"获取列表中"];
    [c addTarget:self action:@selector(requestVideosList) forControlEvents:UIControlEventValueChanged];
    self.refreshControl = c;
}

- (void)requestMovieListSuccess
{
    NSString *str = @"http://localhost:8080/MJServer/video?method=get&type=JSON";
    NSURL *url = [NSURL URLWithString:str];
    NSURLRequest *urlrequest = [NSURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:urlrequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
    NSArray *arr = dict[@"videos"];
    self.list = [NSMutableArray array];
    
    for (NSDictionary *d in arr)
    {
        Video *v = [[Video alloc]initWithDict:d];
        [self.list addObject:v];
    }
    [self.tableView reloadData];
        [self.refreshControl endRefreshing];
    }];

}
- (void)requestMovieListFail
{
    NSString *str = @"http://localhost:8080/MJServer/video?method=get&type=JSON";
    NSURL *url = [NSURL URLWithString:str];
    NSURLRequest *urlrequest = [NSURLRequest requestWithURL:url];
    
    [NSURLConnection sendAsynchronousRequest:urlrequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
    NSLog(@"%@",connectionError,[connectionError localizedDescription]);
    NSString *message = [NSString stringWithFormat:@"连接错误:%@",[connectionError localizedDescription]];
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"错误" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self dismissViewControllerAnimated:YES completion:nil];
        
    }];
    [alert addAction:action];
        [self.refreshControl endRefreshing];
    }];
}



    - (void)requestVideosList
    {
        NSString *str = @"http://localhost:8080/MJServer/video?method=get&type=JSON";
        NSURL *url = [NSURL URLWithString:str];
        NSURLRequest *urlrequest = [NSURLRequest requestWithURL:url];
        
        [NSURLConnection sendAsynchronousRequest:urlrequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
                if (connectionError == nil)
                {
                    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
                    NSArray *arr = dict[@"videos"];
                    self.list = [NSMutableArray array];
                    
                    for (NSDictionary *d in arr)
                    {
                        Video *v = [[Video alloc]initWithDict:d];
                        [self.list addObject:v];
                    }
                    [self.tableView reloadData];
                }
                    else
                    {
                        // 连接失败
                        NSLog(@"%@",connectionError,[connectionError localizedDescription]);
                        NSString *message = [NSString stringWithFormat:@"连接错误:%@",[connectionError localizedDescription]];
                        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"错误" message:message preferredStyle:UIAlertControllerStyleAlert];
                        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                            [self dismissViewControllerAnimated:YES completion:nil];
                            
                        }];
                        [alert addAction:action];
                        [self presentViewController:alert animated:YES completion:nil];
    
                    }
                [self.refreshControl endRefreshing];
            }];
        }

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
     return self.list.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    
    Video *v = self.list[indexPath.row];
    cell.textLabel.text = v.name;
    cell.detailTextLabel.text = [NSString stringWithFormat:@"时长：%i",v.length];
    NSString *urlImageView = [NSString stringWithFormat:@"http://localhost:8080/MJServer/%@",v.image];
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:urlImageView] placeholderImage:[UIImage imageNamed:@"minion_01.png"]];
    return cell;
}





@end
